<?php
declare (strict_types = 1);
namespace app\course\model\coupon;

use app\common\model\BaseModel;
use app\course\model\base\Course;
use app\school\model\school\School;
use think\model\relation\BelongsTo;
use think\model\relation\HasMany;
use think\model\relation\HasOne;

/**
 * 卡券模型 - 均为可用或可领取的存在肯定条件的卡券
 */
class Coupon extends BaseModel
{
    /**
     * 表名
     * @var string
     */
    protected $name = 'coupon';

    /**
     * 设置自动写入时间
     * @var boolean
     */
    protected $autoWriteTimestamp = true;
    protected $updateTime         = false;
    protected $hidden             = ['delete_time'];
    protected $append             = ['school', 'course_title'];

    /**
     * 定义字段类型
     * @var array
     */
    protected $type = [
        'id'          => 'integer',
        'delete_time' => 'integer',
        'create_time' => 'integer',
    ];

    /**
     * 剩余数量
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-16
     *
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getRestAttr($value, $data)
    {
        return $data['count'] - $data['receive_count'];
    }

// 查询范围

// 单条件
    public function scopeUseStime($query)
    {
        $query->where('use_stime', '<', time());
    }

    public function scopeUseEtime($query)
    {
        $query->where('use_etime', '>', time());
    }

    public function scopeCanUse($query)
    {
        $query->whereColumn('count', '>', 'receive_count');
    }

    public function scopeUndelete($query)
    {
        $query->whereNull('delete_time');
    }

    public function scopeInDeriveTime($query)
    {
        $query->where('derive_stime', '<', time())->where('derive_etime', '>', time());
    }

    public function scopeMhm($query, $id = 0)
    {
        $query->where('mhm_id', $id);
    }

    public function scopeMaxprice($query, $price = 0)
    {
        $query->where('maxprice', '<=', $price);
    }

    public function scopeOrderPrice($query, $order = 'ASC')
    {
        $query->order('price ' . $order);
    }

    public function scopeCouponType($query, $type)
    {
        if (is_numeric($type)) {
            $query->where('coupon_type', $type);
        } else {
            $query->where('coupon_type', 'IN', $type);
        }
    }

// 复合条件

    /**
     * 可领取的卡券
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-04-27
     */
    public function scopeCanDerive($query, $id = 0)
    {
        if ( $id ) {
            $query->where('id', $id);   // 指定卡券可领取状态
        }
        $query->where('online', 1);                         // 线上卡
        $query->where('use_etime', '>', time());            // 使用时间、未过期
        $query->whereNull('delete_time');                   // 未删除
        $query->whereColumn('count', '>', 'receive_count'); // 未领完
        $query->where('derive_stime', '<', time());         // 领取开始时间后
        $query->where('derive_etime', '>', time());         // 领取结束时间内
    }

    /**
     * 可兑换的线下卡券
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-04-27
     */
    public function scopeCanExchange($query)
    {
        $query->where('use_etime', '>', time());            // 使用时间、未过期
        $query->whereNull('delete_time');                   // 未删除
    }


    /**
     * 根据类型获取机构可领取卡券
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-04-23
     * @param    [type]                      $mhm_id [机构ID]
     * @param    [type]                      $type   [卡券类型]
     */
    public function scopeMhmDeriveCoupon($query, $mhm_id, $type)
    {
        $query->where('mhm_id', $mhm_id);
        if (is_numeric($type)) {
            $query->where('coupon_type', $type);
        } else {
            $query->where('coupon_type', 'in', $type);
        }
    }

    /**
     * 已领取的可用卡券
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-04-27
     */
    public function scopeHasDerived($query)
    {
        $query->where('use_stime', '<', time());   // 开始使用时间之后
        $query->where('use_etime', '>', time());   // 结束使用时间之前
        $query->whereNull('delete_time');          // 未删除
    }

    /**
     * 当前购物车可用机构卡券
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-04-23
     * @param    [type]                      $mhm_id [机构ID]
     * @param    [type]                      $price  [商品总价]
     * @param    [type]                      $type   [卡券类型]
     */
    public function scopeCartMhmCoupon($query, $mhm_id, $price, $type)
    {
        $query->where('mhm_id', $mhm_id);
        $query->where('maxprice', '<=', $price);
        if (is_numeric($type)) {
            $query->where('coupon_type', $type);
        } else {
            $query->where('coupon_type', 'in', $type);
        }
    }


// 关联

    public function couponUser(): HasMany
    {
        return $this->hasMany(CouponUser::class);
    }

    public function couponUserDerive(): HasMany
    {
        return $this->hasMany(CouponUser::class)->where('user_id', request()->mid)->where('status', 0);
    }

    public function school(): BelongsTo
    {
        return $this->belongsTo(School::class, 'mhm_id')->bind(['school_name' => 'title']);
    }

    public function courseTitle(): BelongsTo
    {
        return $this->belongsTo(Course::class, 'course_id')->bind(['course_title' => 'title']);
    }

    public function courseSolo(): BelongsTo
    {
        return $this->belongsTo(Course::class, 'course_id')->bind(['solo']);
    }

    // 用户领取了的卡券
    public function userHas(): HasOne
    {
        return $this->hasOne(CouponUser::class)->where('user_id', request()->mid);//->bind(['user_has' => 'id']);
    }

    // 用户领取了的卡券且未使用
    public function userHasUnused(): HasOne
    {
        return $this->hasOne(CouponUser::class)->where('user_id', request()->mid)->where('status', 0)->bind(['user_has' => 'id']);
    }
}
